
#include "physics_vehicle.h"
#include "render.h"

using namespace WtfEngine;

Vehicle::Vehicle(const Vehicle::tCreationOptions &opts, const WtfGraphics::GraphicsData::tCacheRef &rChassisGraphics,
				 const PhysicalModel::tCacheRef &rChassisModel):
Physical(opts, rChassisGraphics, rChassisModel, false) {
	mTuning.m_suspensionStiffness = opts.SuspensionStiffness;
	mTuning.m_suspensionDamping = opts.SuspensionDamping;
	mTuning.m_suspensionCompression = opts.SuspensionCompression;

	mpRaycastVehicle = new btRaycastVehicle(mTuning, this->getBody(),
		new btDefaultVehicleRaycaster(PhysicsEngine::GetInstance().getWorld()));

	PhysicsEngine::GetInstance().getWorld()->addVehicle(mpRaycastVehicle);
};


void Vehicle::AddWheel(const tVector &vPos, const WtfGraphics::GraphicsData::tRef &rWheelGfx, const Orientation3D& wheelOri,
				  const tVector &vAxle, const tVector &vMountPoint, tScalar radius, bool isFrontWheel)
{
	mpRaycastVehicle->addWheel(FROMVECT(vMountPoint), FROMVECT((vPos - vMountPoint).normalize()), FROMVECT(vAxle),
		(vPos - vMountPoint).length(), radius, mTuning, isFrontWheel).m_clientInfo
		= new WheelInfo(wheelOri, rWheelGfx);
};

void Vehicle::Render() {
	btScalar m[16];
	int n, i;

	n = mpRaycastVehicle->getNumWheels();

	for(i = 0; i < n; i++) {
		mpRaycastVehicle->updateWheelTransform(i);
		mpRaycastVehicle->getWheelTransformWS(i).getOpenGLMatrix(m);

		glPushMatrix();
		glMultMatrixf(m);
		
		((WheelInfo *)mpRaycastVehicle->getWheelInfo(i).m_clientInfo)->Orientation.getOpenGLMatrix(m);
		glMultMatrixf(m);
	
		((WheelInfo *)mpRaycastVehicle->getWheelInfo(i).m_clientInfo)->rWheelGraphics->render();

		glPopMatrix();
	};

	Physical::Render();
};
